#import "AppDelegate+AppService.h"
#import <UMSocialCore/UMSocialCore.h>
#import "OmLoginVC.h"
#import "AdPageView.h"
#import "RootWebViewController.h"
#import "OpenUDID.h"
@implementation AppDelegate (AppService)
#pragma mark ————— 初始网络请求库 —————
-(void)initYTKNetWork
{
    YTKNetworkConfig *netConfig = [YTKNetworkConfig sharedConfig];
    netConfig.baseUrl = URL_main;
    NSLog(@"%@", URL_main);
    netConfig.cdnUrl = URL_main;
    netConfig.debugLogEnabled = YES;
}
#pragma mark ————— 初始化键盘 —————
-(void)initKeyBoard
{
    [IQKeyboardManager sharedManager].enable = YES;
    [IQKeyboardManager sharedManager].toolbarDoneBarButtonItemText = ASLocalizedString(@"完成");
}
#pragma mark ————— 初始化服务 —————
-(void)initService{
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(loginStateChange:)
                                                 name:KNotificationLoginStateChange
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(netWorkStateChange:)
                                                 name:KNotificationNetWorkStateChange
                                               object:nil];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self initConfig];
    });
}
-(void)initHeartbeat
{
    if(self.heartbeat == nil)
    {
        self.heartbeat = [NSTimer scheduledTimerWithTimeInterval:10 target:self selector:@selector(doHeartbeat) userInfo:nil repeats:YES];
    }
}
-(void)doHeartbeat
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"app_api" A:@"interval"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
        NSLog(@"%@", ASLocalizedString(@"================心跳"));
    } success:^(id responseObject) {
    } failure:^(NSString *error) {
        BOOL loadStatus = [[UserManager sharedUserManager] loadUserInfo];
        NSLog(ASLocalizedString(@"================心跳2%d"),loadStatus);
    } hasCache:NO];
}
-(void)initLocation
{
    if ([CLLocationManager locationServicesEnabled]) {
        self.locationmanager = [[CLLocationManager alloc]init];
        self.locationmanager.delegate = self;
        [self.locationmanager requestAlwaysAuthorization];
        self.currentCity = [NSString new];
        [self.locationmanager requestWhenInUseAuthorization];
        self.locationmanager.desiredAccuracy = kCLLocationAccuracyBest;
        self.locationmanager.distanceFilter = 5.0;
        [self.locationmanager startUpdatingLocation];
    }
}
#pragma mark 定位成功后则执行此代理方法
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    [self.locationmanager stopUpdatingHeading];
    CLLocation *currentLocation = [locations lastObject];
    CLGeocoder *geoCoder = [[CLGeocoder alloc]init];
    NSLog(ASLocalizedString(@"当前的经度与纬度%f,%f"),currentLocation.coordinate.latitude,currentLocation.coordinate.longitude);
    self.strlatitude = NSStringFormat(@"%f",currentLocation.coordinate.latitude);
    self.strlongitude = NSStringFormat(@"%f",currentLocation.coordinate.longitude);
    [geoCoder reverseGeocodeLocation:manager.location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (placemarks.count > 0) {
            CLPlacemark *placeMark = placemarks[0];
            self.currentCity = placeMark.locality;
            if(placeMark.locality == nil)
            {
                self.currentCity = placeMark.administrativeArea;
            }
            if (!self.currentCity) {
                self.currentCity = ASLocalizedString(@"无法定位当前城市");
            }
            NSLog(@"----%@",placeMark.country);
            NSLog(@"%@",self.currentCity);
            NSLog(@"%@",placeMark.subLocality);
        }
    }];
}
#pragma mark CoreLocation delegate (定位失败)
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
}
#pragma mark ————— 初始化window —————
-(void)initWindow{
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = KWhiteColor;
    [self.window makeKeyAndVisible];
    [[UIButton appearance] setExclusiveTouch:YES];
    [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = KWhiteColor;
    if (@available(iOS 11.0, *)){
        [[UIScrollView appearance] setContentInsetAdjustmentBehavior:UIScrollViewContentInsetAdjustmentNever];
    }
}
#pragma mark ————— 初始化用户系统 —————
-(void)initUserManager{
    DLog(ASLocalizedString(@"设备IMEI ：%@"),[OpenUDID value]);
    if([userManager loadUserInfo]){
        self.mainTabBar = [MainTabBarController new];
        self.window.rootViewController = self.mainTabBar;
        [userManager autoLoginToServer:^(BOOL success, NSString *des) {
            if (success) {
                DLog(ASLocalizedString(@"自动登录成功"));
                KPostNotification(KNotificationAutoLoginSuccess, nil);
            }else{
                [MBProgressHUD showErrorMessage:NSStringFormat(ASLocalizedString(@"自动登录失败：%@"),des)];
            }
        }];
    }else{
        KPostNotification(KNotificationLoginStateChange, @NO)
    }
}
#pragma mark ————— 登录状态处理 —————
- (void)loginStateChange:(NSNotification *)notification
{
    BOOL loginSuccess = [notification.object boolValue];
    if (loginSuccess) {
        [self doHeartbeat];
        if (!self.mainTabBar || ![self.window.rootViewController isKindOfClass:[MainTabBarController class]]) {
            self.mainTabBar = [MainTabBarController new];
            CATransition *anima = [CATransition animation];
            anima.type = @"cube";
            anima.subtype = kCATransitionFromRight; 
            anima.duration = 0.3f;
            self.window.rootViewController = self.mainTabBar;
            [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
        }
    }else {
        self.mainTabBar = nil;
        UINavigationController *loginNavi = [[UINavigationController alloc]initWithRootViewController:[[OmLoginVC alloc] init]];
        loginNavi.navigationBar.translucent = NO;
        loginNavi.navigationBar.tintColor = [UIColor whiteColor];
        NSMutableDictionary *titleTextAttributes=[NSMutableDictionary dictionary];
        [titleTextAttributes setObject:[UIColor whiteColor] forKey:NSForegroundColorAttributeName];
        loginNavi.navigationBar.titleTextAttributes = titleTextAttributes;
        [loginNavi.navigationBar setBackgroundImage:[OmHandyMethods imageFromColor:HexadecimalColor(@"FC7CB5") gradientToColor:HexadecimalColor(@"FCA7A1") frame:CGRectMake(0, 0, WINDOW_WIDTH, 64)] forBarMetrics:UIBarMetricsDefault];
        CATransition *anima = [CATransition animation];
        anima.type = @"fade";
        anima.subtype = kCATransitionFromRight; 
        anima.duration = 0.3f;
        self.window.rootViewController = loginNavi;
        [kAppWindow.layer addAnimation:anima forKey:@"revealAnimation"];
    }
}
#pragma mark ————— 网络状态变化 —————
- (void)netWorkStateChange:(NSNotification *)notification
{
    BOOL isNetWork = [notification.object boolValue];
    if (isNetWork) {
        [self initConfig];
        if ([userManager loadUserInfo] && !isLogin) {
            [userManager autoLoginToServer:^(BOOL success, NSString *des) {
                if (success) {
                    DLog(ASLocalizedString(@"网络改变后，自动登录成功"));
                    KPostNotification(KNotificationAutoLoginSuccess, nil);
                }else{
                    [MBProgressHUD showErrorMessage:NSStringFormat(ASLocalizedString(@"自动登录失败：%@"),des)];
                }
            }];
        }
    }else {
        [MBProgressHUD showTopTipMessage:ASLocalizedString(@"网络状态不佳")isWindow:YES];
    }
}
#pragma mark ————— 友盟 初始化 —————
-(void)initUMeng{
    [[UMSocialManager defaultManager] openLog:YES];
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMengKey];
    [self configUSharePlatforms];
}
#pragma mark ————— 配置第三方 —————
-(void)configUSharePlatforms{
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:kAppKey_Wechat appSecret:kSecret_Wechat redirectURL:nil];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:kAppKey_Tencent  appSecret:nil redirectURL:nil];
}
#pragma mark ————— OpenURL 回调 —————
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    BOOL result = [[UMSocialManager defaultManager] handleOpenURL:url sourceApplication:sourceApplication annotation:annotation];
    if (!result) {
    }
    return result;
}
#pragma mark ————— 网络状态监听 —————
- (void)monitorNetworkStatus
{
    [PPNetworkHelper networkStatusWithBlock:^(PPNetworkStatusType networkStatus) {
        switch (networkStatus) {
            case PPNetworkStatusUnknown:
                DLog(ASLocalizedString(@"网络环境：未知网络"));
            case PPNetworkStatusNotReachable:
                DLog(ASLocalizedString(@"网络环境：无网络"));
                KPostNotification(KNotificationNetWorkStateChange, @NO);
                break;
            case PPNetworkStatusReachableViaWWAN:
                DLog(ASLocalizedString(@"网络环境：手机自带网络"));
            case PPNetworkStatusReachableViaWiFi:
                DLog(ASLocalizedString(@"网络环境：WiFi"));
                KPostNotification(KNotificationNetWorkStateChange, @YES);
                break;
        }
        if(networkStatus == PPNetworkStatusReachableViaWWAN || networkStatus == PPNetworkStatusReachableViaWiFi)
        {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self initConfig];
            });
        }
    }];
}
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    BOOL result = [[UMSocialManager defaultManager]  handleOpenURL:url options:options];
    return YES;
}
-(void)AlipayWithResutl:(NSDictionary *)resultDic{
    NSString  *str = [resultDic objectForKey:@"resultStatus"];
    if (str.intValue == 9000)
    {
        [HUDHelper alert:ASLocalizedString(@"支付成功")];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PayResult" object:@"ali_success" userInfo:nil];
    }
    else
    {
        [HUDHelper alert:ASLocalizedString(@"支付失败")];
        [[NSNotificationCenter defaultCenter] postNotificationName:@"PayResult" object:@"fail" userInfo:nil];
    }
}
-(void)initConfig
{
    NSString *url = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"app_api" A:@"config"];
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [CYNET POST:url parameters:param responseCache:^(id responseObject) {
    } success:^(id responseObject) {
        [MBProgressHUD hideHUD];
        KGlobalVariable.appmodel = [AppConfig modelWithDictionary:responseObject];
        KPostNotification(KinitConfigLoginSuccess, nil);
        if(StrValid(KGlobalVariable.appmodel.sdkappid))
        {
            curUser.sdkappid = KGlobalVariable.appmodel.sdkappid;
        }
        [[IMManager sharedIMManager] initIM];
        [[IMManager sharedIMManager] IMLogin:@"" IMPwd:@"" completion:^(BOOL success, NSString *des) {
        }];
        NSString *Furl = [[CYURLUtils sharedCYURLUtils] makeURLWithC:@"user_api" A:@"is_agency"];
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [CYNET POST:Furl parameters:parameters responseCache:nil success:^(id responseObject) {
            [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"DaiLiQuanXian"];
        } failure:^(NSString *error) {
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"DaiLiQuanXian"];
        } hasCache:NO];
    } failure:^(NSString *error) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self initConfig];
        });
    } hasCache:NO];
}
+ (AppDelegate *)shareAppDelegate{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}
-(UIViewController *)getCurrentVC{
    UIViewController *result = nil;
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    return result;
}
-(UIViewController *)getCurrentUIVC
{
    UIViewController  *superVC = [self getCurrentVC];
    if ([superVC isKindOfClass:[UITabBarController class]]) {
        UIViewController  *tabSelectVC = ((UITabBarController*)superVC).selectedViewController;
        if ([tabSelectVC isKindOfClass:[UINavigationController class]]) {
            return ((UINavigationController*)tabSelectVC).viewControllers.lastObject;
        }
        return tabSelectVC;
    }else
        if ([superVC isKindOfClass:[UINavigationController class]]) {
            return ((UINavigationController*)superVC).viewControllers.lastObject;
        }
    return superVC;
}
@end
